package db

import (
	"GameServer/common/logger"
	"GameServer/pb"
	"GameServer/redis"
	"encoding/json"
	"errors"
	"time"
)

//dtb_user_level
type UserLevelInfo struct {
	Uuid        int32
	Battle_id   string
	Level_id    int32
	Start_time  int32
	End_time    int32
	Level_state int32
}

func UpdateLevelInfo(uid uint32, req *pb.GameLevelStartReq, state int32) error {
	cmd := ""
	nowt := int(time.Now().Unix())

	// *******************************
	if redis.GetRedisIsOpen() {
		info := new(UserLevelInfo)
		if state != 0 {
			val, err := redis.GetRedisClient().HGet(redis.GS_USERLEVEL_INFO, req.BattleId)
			if err != nil {
				logger.Error("UpdateLevelInfo failed err=%v", err)
				return err
			}
			err = json.Unmarshal([]byte(val), info)
			if err != nil {
				logger.Error("UpdateLevelInfo json failed err=%v", err)
				return err
			}

			info.End_time = int32(nowt)
			info.Level_state = state
		} else {
			info.Uuid = int32(uid)
			info.Battle_id = req.BattleId
			info.Level_id = req.LevelId
			info.Start_time = int32(nowt)
			info.End_time = int32(0)
			info.Level_state = state
		}

		val, err := json.Marshal(info)
		if err != nil {
			logger.Error("UpdateLevelInfo err=%v", err)
			return err
		}

		err = redis.GetRedisClient().HSet(redis.GS_USERLEVEL_INFO, req.BattleId, string(val))

		if err != nil {
			logger.Error("UpdateLevelInfo err=%v", err)
			return err
		}
		return nil
	}
	// *******************************

	if state == 0 {
		cmd = "insert into dtb_user_level(uuid,battleid,levelid,start_time,finish_time,level_state) values(?,?,?,?,?,?)"
		_, err := m_game_db.Query(cmd, uid, req.BattleId, req.LevelId, nowt, 0, state)
		if err != nil {
			logger.Error("UpdateLevelInfo err=%v", err)
			return err
		}

		return nil
	}

	cmd = "update dtb_user_level set finish_time = ?,level_state = ? where uuid = ? and battleid = ? and levelid = ?"
	_, err := m_game_db.Query(cmd, nowt, state, uid, req.BattleId, req.LevelId)
	if err != nil {
		logger.Error("UpdateLevelInfo err=%v", err)
		return err
	}

	return nil

}

func CheckLevelStart(levelid int32, battleid string, uid uint32, state int32) error {
	instat := 1
	dbstat := 0
	if state != 0 {
		instat = 2
	}

	// *******************************
	if redis.GetRedisIsOpen() {
		info := new(UserLevelInfo)

		val, err := redis.GetRedisClient().HGet(redis.GS_USERLEVEL_INFO, battleid)
		if err != nil {
			logger.Error("CheckLevelStart failed err=%v", err)
			return err
		}
		err = json.Unmarshal([]byte(val), info)
		if err != nil {
			logger.Error("CheckLevelStart json failed err=%v", err)
			return err
		}

		if info.Level_state != 0 {
			logger.Notic("CheckLevelStart Level Stat Not Right")
			return errors.New("Level Stat Not Right")
		}

		info.Level_state = int32(instat)
		info.End_time = int32(time.Now().Unix())

		newval, err := json.Marshal(info)
		if err != nil {
			logger.Error("CheckLevelStart err=%v", err)
			return err
		}

		err = redis.GetRedisClient().HSet(redis.GS_USERLEVEL_INFO, battleid, string(newval))

		if err != nil {
			logger.Error("CheckLevelStart err=%v", err)
			return err
		}
		return nil
	}
	// *******************************

	cmd := "select level_state from dtb_user_level where levelid = ? and battleid = ? and uuid = ?"
	rows, err := m_game_db.Query(cmd, levelid, battleid, uid)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("CheckLevelStart Scan error:%v", err)
		return err
	}
	for rows.Next() {
		err = rows.Scan(&dbstat)
		if err != nil {
			logger.Notic("CheckLevelStart Scan error:%v", err)
			return err
		}
	}

	if dbstat != 0 {
		logger.Notic("CheckLevelStart Level Stat Not Right")
		return errors.New("Level Stat Not Right")
	}

	//需要更新状态
	cmd = "update dtb_user_level set level_state = ?,finish_time = ? where levelid = ? and battleid = ? and uuid = ?"
	_, err = m_game_db.Exec(cmd, instat, int(time.Now().Unix()), levelid, battleid, uid)
	if err != nil {
		logger.Notic("CheckLevelStart Scan error:%v", err)
		return err
	}
	return nil
}

func CheckLevelFin(uuid uint32, levelid int32) error {
	//临时关闭
	return nil
	cnt := 0
	cmd := "select count(*) from dtb_user_level where uuid = ? and levelid = ? and level_state = 1"
	rows, err := m_game_db.Query(cmd, uuid, levelid)
	if rows != nil {
		defer rows.Close()
	}
	if err != nil {
		logger.Notic("CheckLevelFin Scan error:%v", err)
		return err
	}

	for rows.Next() {
		err = rows.Scan(&cnt)
		if err != nil {
			logger.Notic("CheckLevelFin Scan error:%v", err)
			return err
		}
	}

	if cnt < 1 {
		return errors.New("CheckLevelFin not finished")
	}
	return nil
}
